import React from 'react'
import { inject, observer } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Tools,Toast } from 'weaver-mobile';
import { RouteLayout,DocumentTitle } from 'weaver-mobile-page';
import * as mobx from 'mobx';
import {_chooseInvoice,_scanQRCode,getCpUser,getLang} from '../util/pulic-func'
import './style/invoiceScanning.less';
const getLabel = Tools.getLabel;

@inject('scanningPageStore')
@withRouter
@observer
export default class ScanningPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            onRowSelectArr:[]
        }

    }
    
    componentWillMount(){
        const {scanningPageStore} = this.props;
        const { getTheme,getEquipmentFn } = scanningPageStore;
        getTheme();
        getEquipmentFn();
    }    

    componentDidMount() {
        this.initFunction();

        window.addEventListener('message', this.receiver, false);
    }

    componentWillUnmount() {

        window.removeEventListener('message', this.receiver, false)
    }

    render() {
        const { scanningPageStore, history } = this.props;
        const { invoiceCloudInfo,cloudInvoiceId,equipment } = scanningPageStore;
		let lang = getLang();


        return (
            <div style={{ height: "100%" }}>
                <DocumentTitle data={[{ match: /^\/req\/fnaInvoiceScanning/i, title: () => getLabel(516432,'发票录入') }]} defaultTitle="" />
                {this.getComment()}

                <RouteLayout.Frame
                    id="invoiceframe"
                    path={'/wallet/invoiceframe'}
                    iframeProps={{
                        src: `${invoiceCloudInfo.jsUrl}/invoiceWeb/taro/dist/h5/#/pages/service/preview?token=${invoiceCloudInfo.token}&id=${cloudInvoiceId}&src=EC&dev=${equipment.dev}&lang=${lang}`,
                    }}
                />
            </div>
        );
    }

    initFunction = () =>{
        const { scanningPageStore,baseParam } = this.props;
        const { getEnterInvoiceTap,getInvoiceCloudToken,getFieldId } = scanningPageStore;
        let dindex = this.getWfDetailName();
        if(dindex == "main"){
            dindex = 0;
        }else{
            dindex = dindex.split('_')[1]
        }

        getFieldId({
            dindex:dindex,
            workflowid:baseParam.workflowid
        },(data)=>{
            // let rowIndex = this.getWfRowIndex(dindex);
            // let rowIndex_array = rowIndex.split(",");
            // let _onRowSelectArr = [];
            // for(let rowIdx = 0; rowIdx < rowIndex_array.length; rowIdx++){
            //     let idx = rowIndex_array[rowIdx];
            //     let invoiceid = window.WfForm.getFieldValue("field" + data.fieldId + "_" + idx);
            //     invoiceid = invoiceid ? invoiceid.toString() : invoiceid;               
            //     _onRowSelectArr.push(invoiceid);
            // }
            // this.setState({
            //     onRowSelectArr:_onRowSelectArr
            // })
            getEnterInvoiceTap();
            getInvoiceCloudToken();
            
        },()=>{this.props.history.go(-1);})
        
    }

    getComment = () => {
        const { scanningPageStore } = this.props;
        const { invoiceCloudInfo,enabled,theme,equipment } = scanningPageStore;
        let _enabled = JSON.stringify(enabled);
		let lang = getLang();

        if (invoiceCloudInfo.invoiceCloud === true) {
            let comment = <iframe
                className='ec-iframe'
                src={`${invoiceCloudInfo.jsUrl}/invoiceWeb/taro/dist/h5/#/pages/service/expense/ec?token=${invoiceCloudInfo.token}&disabledInvoice=${encodeURIComponent(JSON.stringify(this.state.onRowSelectArr))}&enabled=${encodeURIComponent(_enabled)}&theme=${encodeURIComponent(JSON.stringify(theme))}&src=EC&dev=${equipment.devNum}&lang=${lang}`}
                style={{ width: '100%', height: '100%', border: '0' }}
                id={'myIframe'}
            >
            </iframe>
            return comment;
        }

    }

    /* ***********************发票云********************************/
    receiver = (event) => {
        const { scanningPageStore } = this.props;
        const { setCloudInvoiceId,equipment,invoiceCloudInfo } = scanningPageStore;
        if (invoiceCloudInfo.jsUrl != event.origin) return;
        let returnData = event.data;

        switch(returnData.type){
            case 'INVOICE' :
                let arr = [];
                returnData.invoices.map( items =>{
                    arr.push(items.oaid)
                })
                this.backFu(arr);
                
                break;
            case 'ERROR':
                if(returnData.ret == '-2'){
                    this.sendResult('UPDATE_TOKEN');
                }
                break;
            case 'ON_PREVIEW' : 
                this.props.history.push('/wallet/invoiceframe');
                setCloudInvoiceId(returnData.invoiceId);
                break;
            case 'ON_SCAN_QRCODE' : //调用扫码
                _scanQRCode((value) =>{
                    let params = {
                        source: "ENTRY",
                        type: "SCAN_QRCODE",
                        rid: returnData.rid , // 发票云传过来的 id
                        result: value, // 扫码结果
                    }

                    this.sendResult('SCAN_QRCODE',params);
                    
                });
                break; 
            case 'ON_SELECT_INVOICE': //选择发票   类型：1 微信  2 支付宝
                _chooseInvoice(returnData.invoiceType,(value)=>{
                    let params = {
                        source: "ENTRY",
                        type: "SELECT_INVOICE",
                        invoiceType: returnData.invoiceType, // 类型：1 微信  2 支付宝
                        rid: returnData.rid, // 发票云传过来的 id
                        list: value,
                    }
                    if(equipment.isWx === false){
                        getCpUser((value)=>{
                            params = Object.assign(params,{
                                appKey: value
                            });
                            this.sendResult('SELECT_INVOICE',params);
                        })
                        
                    }else{
                        this.sendResult('SELECT_INVOICE',params);
                    }

                });
                break;    
            case 'ON_CHOOSE_IMAGE':
                this.takePicture(this,{rid:returnData.rid});
                break;                                                  
            default :
                break;
        }
        

    }
    
    //发送数据到 iframe
    sendResult = (type,data)=>{
        const {scanningPageStore} = this.props;
        const {getInvoiceCloudToken} = scanningPageStore;

        let that = this;
        switch(type){
            case 'UPDATE_TOKEN' :
                getInvoiceCloudToken({tokenUnusual:1},()=>{
                    that.sendMessage({
                        type: 'UPDATE_TOKEN',
                        token: scanningPageStore.invoiceCloudInfo.token
                    });
                })
                break;
            case 'SCAN_QRCODE' :  
                that.sendMessage(data)
                break;
            case 'SELECT_INVOICE' :  
                that.sendMessage(data)
                break;
            case 'CHOOSE_IMAGE':
                that.sendMessage(data)
                break;
        }

    }

    //统一发送数据
    sendMessage = (data) =>{
        const {scanningPageStore} = this.props;

        let childFrame = document.getElementById("myIframe");
        let url = scanningPageStore.invoiceCloudInfo.jsUrl;
        childFrame.contentWindow.postMessage(data, url); 
    }

    //获取所有 发票拍照数据
    getlocalIdData = (params,data,send) =>{
        if(send){ 
            let localParams = {
                source: "ENTRY",
                type: "CHOOSE_IMAGE",
                rid: params.rid, // 发票云传过来的 id,
                list:data
                
            }

            this.sendMessage(localParams);
            
        }
    }     

    //拍照
    takePicture = (e,params) =>{
        const isExist = window.em_ssoInit && window.em && window.em.checkJsApi('chooseImage');
        if (!isExist) {Toast.fail(getLabel(525804,'对不起,暂不支持该应用'));return};

        let that = this;
        let localIdArr = [];
        let num = 0;
        window.em_ssoInit().then(() => {

            window.em.chooseImage({
                count: 10, // 最大可选照片数，默认9
                sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    let localIds = res.localIds; // 返回选定照片的本地ID列表
                    localIds.forEach(function(localId){
                        window.em.getLocalImgData({
                            localId: localId,
                            success: function(res){
								num++;
                                let data = res.localData;
                                let base64PicData = "data:image/jpeg;base64,"+data;
                                let bool = localIds.length == num ? true : false;
                                
                                let listEle = {
                                    base64:base64PicData,
                                    fileName: '',
                                }
                                localIdArr.push(listEle);
                                that.getlocalIdData(params,localIdArr,bool)
                            }
                        });
                    });

                }
            });
        }).catch((res) => {
            alert("连续拍照插件异常,使用原始插件");
            // alert(JSON.stringify(res));
            //var dom="<input type='file' accept='image/*' multiple='multiple' name='file_head' id='file_head' style='position:absolute;opacity:0;margin-top: -50px;height: 50px;width: 33%;'>";
            //$("#chooseInvoice").append(dom);
        })
    }     



    backFu = (invoiceIdArr) => {
        const { scanningPageStore, baseParam } = this.props;
        const { addDetail, fieldId, list } = scanningPageStore;
        let workflowid = baseParam.workflowid;
        let dindex = this.getWfDetailName();

        let rowIndex = this.getWfRowIndex(dindex);
        for (let i = 0; i < invoiceIdArr.length; i++) {
            let rowIndex_array = rowIndex.split(",");
            for (let rowIdx = 0; rowIdx < rowIndex_array.length; rowIdx++) {
                let idx = rowIndex_array[rowIdx];
                let invoiceid = window.WfForm.getFieldValue("field" + fieldId + "_" + idx);
                let sub = invoiceIdArr.indexOf(parseInt(invoiceid));
                if (sub > -1) {
                    invoiceIdArr.splice(sub,1);
                }
            }
        }


        if (invoiceIdArr.length == 0) {
            this.props.history.go(-1);
            return
        }


        if (dindex == "main") {
            dindex = 0;
        } else {
            dindex = parseInt(dindex.split("_")[1]);
        }
        let params = {
            invoiceIds: invoiceIdArr,
            dindex: dindex,
            workflowid: workflowid,
            operate: "addDetail"
        };

        addDetail(params,(value)=>{
            let desc = value.desc;
            let invoiceInfo = value.invoiceInfo;
            let {fieldindex,fieldIdDate,fieldIdSubject,fieldIdAmount,fieldIdInvoice,fieldIdDesc} = invoiceInfo;
    

            if(invoiceInfo.fieldindex == 0){//主表
                let specialobj = JSON.parse(invoiceInfo.specialobj);
                window.WfForm.changeFieldValue("field"+fieldIdInvoice, {
                    value: invoiceInfo.idStr,
                    specialobj:specialobj
                });//发票
                // fieldIdSubject && window.WfForm.changeFieldValue("field"+fieldIdSubject, {value:subjectName});//科目
                // fieldIdAmount && window.WfForm.changeFieldValue("field"+fieldIdAmount, {value:taxIncludedPrice});//金额
                // fieldIdDate && window.WfForm.changeFieldValue("field"+fieldIdDate, {value:billingDate});//日期
                // fieldIdDesc && window.WfForm.changeFieldValue("field"+fieldIdDesc, {value:invoiceServiceYype});//说明
            }else{
                for(let i = 0;i<desc.length;i++){
                    let symbol = this.getWfDetailName();
                    if(symbol != 'main'){
                        window.WfForm.setDetailAddUseCopy(symbol, false);
                    }
                    let detail = "detail_"+fieldindex;
                    let addDetailRow_paramObj = {};
                    addDetailRow_paramObj["field"+fieldIdInvoice] = {value : desc[i].id , specialobj : [{id : desc[i].id, name : desc[i].invoiceNumber}]};//发票
                    if(fieldIdSubject>0){
                      addDetailRow_paramObj["field"+fieldIdSubject] = {value : desc[i].subjectId, specialobj : [{id : desc[i].subjectId, name : desc[i].subjectName}]};//科目
                    }
                    if(fieldIdAmount>0){
                        addDetailRow_paramObj["field"+fieldIdAmount] = {value : desc[i].taxIncludedPrice};//金额
                    }
                    if(fieldIdDate>0){
                        addDetailRow_paramObj["field"+fieldIdDate] = {value : desc[i].billingDate};//日期
                    }
                    if(fieldIdDesc>0){
                        addDetailRow_paramObj["field"+fieldIdDesc] = {value : desc[i].invoiceServiceYype};//说明
                    }
                    window.WfForm.addDetailRow(detail,addDetailRow_paramObj);
                }
            }

            this.props.history.go(-1);
        });        

    }

    //获取流程明细表名
    getWfDetailName = () => {
        const { baseParam, fnaInfo, symbol } = this.props;
        let dataName = this.props.location.search.split("=");

        return dataName[dataName.length - 1];
    }

    //获取所有行 标识
    getWfRowIndex = (detail) => {
        let rowIndex = window.WfForm.getDetailAllRowIndexStr(detail);
        return rowIndex;
    }



    //url参数串转成对象
    transQueryParams = (arg) => {
        let paramStr = typeof arg === "object" ? arg.search : arg;
        if (paramStr.indexOf("?") > -1)
            paramStr = paramStr.substring(paramStr.indexOf("?") + 1);
        let queryParams = {};
        const arr = paramStr.split("&");
        arr && arr.map(item => {
            const single = item.split("=");
            queryParams[single[0]] = single[1];
        });
        return queryParams;
    }
}
